package com.apeli.web.controller.aticle;


import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
public class Blog  {

    volatile AtomicReference<String>  content = new AtomicReference<>("aa11ss54cc");

    public  void replace() {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        List<String> sensorWordList = new ArrayList<>();
        sensorWordList.add("aa");
        sensorWordList.add("ss");
        sensorWordList.add("cc");
        List<List<String>> sensorWords = Lists.partition(sensorWordList, 1);
        CompletableFuture[] completableFutureList = sensorWords.stream().map(sourceData -> CompletableFuture.runAsync(() -> {
            log.info("线程："+ Thread.currentThread().getName() + "开始执行敏感词汇替换...");
            for (String words : sourceData) {
                // 文本内容替换
                synchronized(Blog.class) {
                    content.set(content.get().replaceAll(words, "**"));
                }
            }
        }, executor)).toArray(CompletableFuture[]::new);
        // 等待线程池执行完毕，只有执行完以后才能向下执行，否则敏感词汇没有替换完毕，导致替换遗漏
        CompletableFuture.allOf(completableFutureList).join();

    }

    public void print () {
        System.out.println(content);
    }


}
